import { Context, Next } from 'koa'
import jwt from 'jsonwebtoken'
import config from '../config'
import { TokenValidationException } from '../exception/HttpException'

//验证token方法
export const authToken = async (ctx: Context, next: Next) => {
  const { authorization } = ctx.request.header

  console.log(authorization, 'aut')
  console.log('22')
  //注意这里Bearer后面有一个空格
  if (authorization) {
    const token = authorization.replace('Bearer ', '')

    console.log(token)

    try {
      const JWT_SECRET = config.jwt.jwt_secret
      //user中包含payload的信息(id,usename,is_admin)
      const user = jwt.verify(token, JWT_SECRET as string)
      ctx.state.user = user
    } catch (err: any) {
      switch (err.name) {
        case 'TokenExpiredError':
          console.error('token已过期!', err)
          throw new TokenValidationException(err, 'token已过期!')
        case 'JsonWebTokenError':
          console.error('无效的token')
          //  return ctx.app.emit('error', invalidToken, ctx)
          throw new TokenValidationException(err, '无效的token', 20102)
      }
    }
  } else {
    throw new TokenValidationException('', '登录凭证不存在！', 20103)
  }

  await next()
}
